package bar.dark.lee.memo;

import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class MemoUpdateActivity extends SuperActivity
{
	private DBSQLite sql;
	
	private View dateView;
	private TextView dateTextView;
	
	private EditText titleEditText;
	
	private EditText memoEditText;
	
	private Button insertButton;
	private Button deleteButton;
	
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private MemoData data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(superContext);
		
		setContentView(R.layout.memo_insert_activity);
		
		setTitle("메모 정보 / 수정");
		
		setFindView();
		setOnClickListener();
		
		new ShowDialog().execute(BDUtil.asyncFlag, 0);
	}

	private void setFindView()
	{
		dateView = findViewById(R.id.memoInsertDateView);
		dateTextView = (TextView) findViewById(R.id.memoInsertDateTextView);
		
		titleEditText = (EditText) findViewById(R.id.memoInsertTitleEditText);
		
		memoEditText = (EditText) findViewById(R.id.memoInsertMemoEditText);
		
		insertButton = (Button) findViewById(R.id.memoInsertButton);
		
		deleteButton = (Button) findViewById(R.id.memoInsertDeleteButton);
		
		insertButton.setText("수정");
	}
	
	private void setOnClickListener()
	{
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				DatePickerDialog dialog = new DatePickerDialog(superContext, new OnDateSetListener()
//				{
//					@Override
//					public void onDateSet(DatePicker view, int year, int monthOfYear,
//							int dayOfMonth)
//					{
//						toYear = year;
//						toMonth = monthOfYear;
//						toDay = dayOfMonth;
//						
//						dateTextView.setText(BDUtil.getDate(year, monthOfYear+1, dayOfMonth));
//					}
//				}, toYear, toMonth, toDay);
//				
//				dialog.show();
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
						
						toYear = year;
						toMonth = monthOfYear;
						toDay = dayOfMonth;
						
					}
				}, toYear, toMonth, toDay);
				
				cpd.show();
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (titleEditText.getText().toString().equals(""))
				{
					BDUtil.showDialog(superContext, "경고", "제목을 입력해주세요.");
					return;
				}
				
				if (memoEditText.getText().toString().equals(""))
				{
					BDUtil.showDialog(superContext, "경고", "내용을 입력해주세요.");
					return;
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		});
	}
	
	private void setData()
	{
		String id = getIntent().getStringExtra(MemoListActivity.MEMO_DATA_ID);
		
		if (id == null)
		{
			return;
		}
		
		String query = "";
		
		query = "SELECT * FROM memo_main WHERE id = " + id + ";";
		
		sql.selectMapTile(superContext, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				data = new MemoData();
				
				int idIdx = c.getColumnIndex("id");
				int titleIdx = c.getColumnIndex("title");
				int memoIdx = c.getColumnIndex("memo");
				int dateIdx = c.getColumnIndex("date");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data.setId(c.getInt(idIdx) + "");
					data.setTitle(c.getString(titleIdx));
					data.setMemo(c.getString(memoIdx));
					data.setDate(c.getString(dateIdx));
					
					c.moveToNext();
				}
			}
		});
		
		int [] dates = BDUtil.getDateSet(data.getDate());
		
		toYear = dates[0];
		toMonth = dates[1]-1;
		toDay = dates[2];
	}
	
	private void setUpdateData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("title", titleEditText.getText().toString());
		map.put("memo", memoEditText.getText().toString());
		map.put("date", BDUtil.getDateDB(toYear, toMonth+1, toDay));
		
		String [] whereArgs = new String[]{data.getId()};
		
		sql.update(superContext, "memo_main", map, "id = ?", whereArgs);
	}
	
	private void setDeleteData()
	{
		String [] whereArgs = new String[]{data.getId()};
		
		sql.delete(superContext, "memo_main", "id = ?", whereArgs);
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 0)
				{
					setData();
					
					return arg0[1];
				}
				else if (arg0[1] == 1)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setUpdateData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setDeleteData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				
				return -1;
			}
			else
			{
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.showDialog(superContext, "오류", "메모를 추가하는데 실패 하였습니다.");
			}
			else if (result == 0)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				dateTextView.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
				
				titleEditText.setText(data.getTitle());
				
				memoEditText.setText(data.getMemo());
			}
			else if (result == 1) 
			{
				setResult(Activity.RESULT_OK);
				BDUtil.showDialogFinish(superContext, "알림", "메모가 수정 되었습니다.");
			}
			else if (result == 2)
			{
				setResult(Activity.RESULT_OK);
				BDUtil.showDialogFinish(superContext, "알림", "메모가 삭제 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_MEMO);
		startActivity(intent);
	}
}
